<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'
import lodash from 'lodash'
import router from '@/router'


// 创建 API 客户端实例
const apiClient = axios.create({
  baseURL: 'http://localhost:8085', // 根据实际后端地址修改
  timeout: 10000,
})
const venueApiClient = axios.create({
  baseURL: 'http://localhost:8089', // 场地服务地址
  timeout: 10000,
})
const seatApiClient = axios.create({
  baseURL: 'http://localhost:8089', // 座位服务地址
  timeout: 10000,
})

// 添加请求拦截器，如果需要token认证
apiClient.interceptors.request.use(
    config => {
      // 从localStorage获取token并添加到请求头
      const token = localStorage.getItem('token');
      if (token) {
        config.headers.Authorization = token;
      }
      return config;
    },
    error => {
      return Promise.reject(error);
    }
);

// 添加响应拦截器处理通用逻辑
apiClient.interceptors.response.use(
    response => {
      // 直接返回数据
      return response.data;
    },
    error => {
      // 统一处理错误
      if (error.response && error.response.status === 401) {
        // 未授权，跳转到登录页
        ElMessage.error('认证失败，请重新登录');
        localStorage.removeItem('token');
        router.push('/login');
      } else {
        ElMessage.error('请求失败: ' + (error.response?.data?.msg || error.message));
      }
      return Promise.reject(error);
    }
);



const concertInfo = ref(null)
async function getconcert(){
  try {
    const response = await apiClient.get(`/concert/all`);
    concertInfo.value = response.data;
    console.log(concertInfo.value);
    return concertInfo.value;
  } catch (error) {
    console.error("获取用户信息失败:", error);
    return null;
  }
}


const tableData=ref([]);

const  total=ref(0);
//定义对话框的显示状态
const editWinVisible = ref(false);
// 新增综合对话框显示状态
const addAllWinVisible = ref(false);
//查询数据
const searchObj=ref({
  current:1,
  size:5,
  total:0,
  title:'',
  artist:'',
  venueid:{'venueName':''},
  startsale:'',
  startdate:'',
  enddate:'',
  introduction:'',
  creatdate:'',
  photo:'',
  status:'',
});
//要修改或者新增的数据
const obj=ref({});

// 综合新增表单数据
const addAllForm = ref({
  // 演唱会信息
  concert: {
    title:'',
    artist:'',
    startsale:'',
    startdate:'',
    enddate:'',
    introduction:'',
    creatdate:'',
    photo:'',
    status:'0',
  },
  // 场地信息
  venue: {
    name: '',
    address: '',
    capacity: '',
    contact: ''
  },
  // 座位信息
  seat: {
    area:'看台',
    count:'',
    capacity:'',
    status:'0'
  }
});



// // 获取场地名称的辅助函数
// const getVenueName = async (venueid) => {
//   if (!venueid) return '未知场地';
//   try {
//     const response = await venueApiClient.get(`/venue/getVenueById/${id}`);
//     if (response.data && response.code === 200) {
//       return response.data.data.name;
//     }
//     return '未知场地';
//   } catch (error) {
//     console.error('获取场地信息失败:', error);
//     return '场地信息获取失败';
//   }
// };


const search = async () => {
  try {
    // 使用网关进行分页查询
    const params = {
      current: searchObj.value.current,
      size: searchObj.value.size,
      title: searchObj.value.title,
      artist: searchObj.value.artist,
    };
    console.log('请求参数:', params);
    const response = await apiClient.get('/concert/page', { params });
    console.log('接口响应:', response); // 查看响应结构
    tableData.value = response.data.records || [];
    total.value = response.data.total || 0;
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error('获取用户列表失败');
    tableData.value = [];
    total.value = 0;
  }

}
//页面加载后要挂载的数据
onMounted(async () => {
  await getconcert();
  await search();
});
//定义方法

const handleSizeChange = () => {
  search();
}
const handleCurrentChange = () => {
  search();
}
const handleSearch = async () => {
  searchObj.value.current=1
  search();
}
const handleAdd = () => {
  // 初始化新增对象，包含所有必要字段
  obj.value = {
    title:'',
    artist:'',
    venueid:{'venueName':''},
    startsale:'',
    startdate:'',
    enddate:'',
    introduction:'',
    creatdate:'',
    photo:'',
    status:'0', // 默认启用状态
    // 其他需要的字段
  };
  editWinVisible.value = true;
}

// 打开综合新增对话框
const handleAddAll = () => {
  // 重置表单数据
  addAllForm.value = {
    concert: {
      title:'',
      artist:'',
      startsale:'',
      startdate:'',
      enddate:'',
      introduction:'',
      creatdate:'',
      photo:'',
      status:'0',
    },
    venue: {
      name: '',
      address: '',
      capacity: '',
      contact: ''
    },
    seat: {
      area:'看台',
      count:'',
      capacity:'',
      status:'0'
    }
  };
  addAllWinVisible.value = true;
}




const editCancel = () => {
  obj.value = {};//清空数据
  editWinVisible.value = false;//关闭对话框
}
//关闭综合新增对话框
const addAllCancel = () => {
  addAllWinVisible.value = false;
}

// 提交综合新增信息
const addAllCommit = async () => {
  try {
    // 1. 新增场地信息
    console.log('正在新增场地信息:', addAllForm.value.venue);
    const venueResponse = await venueApiClient.post('/venue/add', addAllForm.value.venue);
    console.log('场地信息新增响应:', venueResponse);

    // 检查响应格式并提取ID
    let venueId = null;
    if (typeof venueResponse === 'object') {
      if (venueResponse.status === 200) {
        venueId = venueResponse.data.data?.id;
        // console.log('场地ID:', venueId);
      } else {
        throw new Error('新增场地信息失败: ' + (venueResponse.msg || venueResponse.message || '未知错误'));
      }
    } else {
      throw new Error('服务器返回了无效的响应格式');
    }

    if (!venueId) {
      throw new Error('无法从响应中提取场地ID');
    }

    ElMessage.success('场地信息新增成功');

    // 2. 新增演唱会信息
    const concertData = { ...addAllForm.value.concert, venueid: venueId };
    console.log('正在新增演唱会信息:', concertData);
    const concertResponse = await apiClient.post('/concert/add', concertData);
    console.log('演唱会信息新增响应:', concertResponse);
    // console.log('正在新增场地信息:', addAllForm.value.concert);
    // const concertResponse = await apiClient.post('/concert/add', addAllForm.value.concert);
    // console.log('场地信息新增响应:', concertResponse);

    // 检查响应格式并提取ID
    let concertId = null;
    if (typeof concertResponse === 'object') {
      if (concertResponse.code === 200) {
        concertId = concertResponse.data?.id;
        console.log('演唱会ID:', concertId);
      } else {
        throw new Error('新增演唱会信息失败: ' + (concertResponse.msg || concertResponse.message || '未知错误'));
      }
    } else {
      throw new Error('服务器返回了无效的响应格式');
    }

    if (!concertId) {
      throw new Error('无法从响应中提取演唱会ID');
    }

    ElMessage.success('演唱会信息新增成功');

    // 3. 新增座位信息
    const seatData = { ...addAllForm.value.seat, concertid: concertId };
    console.log('正在新增座位信息:', seatData);
    const seatResponse = await seatApiClient.post('/seat/add', seatData);
    console.log('座位信息新增响应:', seatResponse);

    // 检查响应格式
    if (typeof seatResponse === 'object') {
      if (seatResponse.status !== 200) {
        throw new Error('新增座位信息失败: ' + (seatResponse.msg || seatResponse.message || '未知错误'));
      }
    } else {
      throw new Error('服务器返回了无效的响应格式');
    }

    ElMessage.success('座位信息新增成功');
    addAllWinVisible.value = false;

    // 刷新表格
    search();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败: ' + (error.message || '未知错误'));
  }
}


const editCommit = async () => {
  // await api.edit(obj.value);//提交修改数据
  // search();//刷新表格
  // editWinVisible.value = false;//关闭编辑对话框
  try {
    if (obj.value.id) {
      // 编辑操作
      await apiClient.put('/concert/edit', obj.value);
      ElMessage.success('编辑成功');
    } else {
      // 新增操作
      await apiClient.post('/concert/add', obj.value);
      ElMessage.success('新增成功');
    }
    search(); // 刷新表格
    editWinVisible.value = false; // 关闭编辑对话框
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败: ' + (error.response?.data?.msg || error.message));
    // 可以添加 Element Plus 的消息提示
    // ElMessage.error('操作失败');
  }
}

const handleEdit = (index, row) => {
  obj.value=lodash.clone(row);
  editWinVisible.value = true;
  console.log(index, row)
}
const prehot = async () => {
  ElMessage.success('预热成功');
}

const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async() => {
        try {
          await apiClient.delete(`/concert/deleteConcert/${row.id}`);
          ElMessage.success('删除成功');
          //重新加载数据
          //设置从第一页开始查询
          searchObj.value.current = 1;
          search();
        } catch (error) {
          ElMessage.error('删除失败: ' + (error.response?.data?.msg || error.message));
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      })
}


// 订单状态文字映射（添加到script setup中）
const getStatusText = (status) => {
  const statusMap = {
    0: '未开售',
    1: '售票中',
    2: '已售空'
    // 如需添加"已过期"可补充：3: '已过期'
  };
  return statusMap[status] || '未知状态'; // 默认显示未知状态
};
</script>

<template>
  <!--搜索-->
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top: 10px">
    <el-form-item label="演唱会标题">
      <el-input v-model="searchObj.title" placeholder="演唱会标题" clearable />
    </el-form-item>
    <el-form-item label="艺人/乐队名称">
      <el-input v-model="searchObj.artist" placeholder="艺人/乐队名称" clearable />
    </el-form-item>
  </el-form>
  <el-form :inline="true">
    <el-form-item>
      <el-button type="primary" @click="handleSearch" style="background-color: #c5a7df; border-color: #c5a7df;">查询</el-button>
    </el-form-item>
    <el-form-item >
      <el-button type="primary" @click="handleAdd" style="background-color: #c5a7df; border-color: #c5a7df;">新增</el-button>
    </el-form-item>
    <!-- 新增综合按钮 -->
    <el-form-item >
      <el-button type="success" @click="handleAddAll" style="background-color: #67c23a; border-color: #67c23a;">发布</el-button>
    </el-form-item>
  </el-form>

  <el-table
      :data="Array.isArray(tableData) ? tableData : []"
      style="width: 100%"
      height="tableHeight"
      v-loading="tableData.length === 0 && total === 0">
    <el-table-column fixed prop="id" label="序号" width="100" />
    <el-table-column prop="title" label="演唱会标题" width="160" />
    <el-table-column prop="artist" label="艺人/乐队名称" width="160" />
    <el-table-column prop="venueName" label="场地名称" width="160" />
<!--    <template #default="scope">-->
<!--      <span v-if="scope.row.venueName">{{getVenueName (scope.row.venueName) }}</span>-->
<!--    </template>-->
<!--    </el-table-column>-->
    <el-table-column prop="startsale" label="开售时间" width="100" />
    <el-table-column prop="startdate" label="演唱会开始时间" width="200" />
    <el-table-column prop="enddate" label="演唱会结束时间" width="200" />
    <el-table-column prop="introduction" label="演唱会简介" width="200" />
    <el-table-column prop="creatdate" label="发布时间" width="200" />
<!--    <el-table-column prop="photo" label="演唱会图片" width="200" />-->
    <el-table-column prop="status" label="状态" width="100" >
    <template #default="scope">
      <!-- 使用映射函数显示文字 -->
      <span>{{ getStatusText(scope.row.status) }}</span>
    </template>
    </el-table-column>
    <el-table-column label="处理按钮">
      <template #default="scope">
        <el-button
            size="small"
            type="warning"
            @click="handleEdit(scope.$index, scope.row)">
           编辑
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)" >
          删除
        </el-button>
        <el-button
            size="small"
            type="success"
            @click="prehot(scope.$index, scope.row)" >
          预热
        </el-button>
      </template>
    </el-table-column>



  </el-table>
  <!--分页-->
  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.size"
      :page-sizes="[10, 20, 30, 40]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"

  />



  <!--   编辑对话框-->

  <el-dialog v-model="editWinVisible" title="编辑" width="500">
    <el-form :model="obj" label-width="110px">
      <el-form-item label="演唱会标题" >
        <el-input v-model="obj.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="艺人/乐队名称">
        <el-input v-model="obj.artist" autocomplete="off" />
      </el-form-item>
      <el-form-item label="场地名称">
        <el-input v-model="obj.venueName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="开售时间" >
        <div class="demo-datetime-picker">
          <div class="block">
            <span class="demonstration"></span>
            <el-date-picker
                v-model="obj.startsale"
                type="datetime"
                placeholder="Select date and time"
            />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="演唱会开始时间" >
        <div class="demo-datetime-picker">
          <div class="block">
            <span class="demonstration"></span>
            <el-date-picker
                v-model="obj.startdate"
                type="datetime"
                placeholder="Select date and time"
            />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="演唱会结束时间" >
        <div class="demo-datetime-picker">
          <div class="block">
            <span class="demonstration"></span>
            <el-date-picker
                v-model="obj.enddate"
                type="datetime"
                placeholder="Select date and time"
            />
          </div>
        </div>
      </el-form-item>
        <el-form-item label="演唱会简介">
        <el-input v-model="obj.introduction" autocomplete="off" />
      </el-form-item>
      <el-form-item label="发布时间" >
        <div class="demo-datetime-picker">
          <div class="block">
            <span class="demonstration"></span>
            <el-date-picker
                v-model="obj.creatdate"
                type="datetime"
                placeholder="Select date and time"
            />
          </div>
        </div>
      </el-form-item>
<!--        <el-form-item label="演唱会图片">-->
<!--        <el-input v-model="obj.photo" autocomplete="off" />-->
<!--      </el-form-item>-->
      <el-form-item label="状态">
        <el-select v-model="obj.status" placeholder="请选择">
          <el-option label="未开售" value="0"></el-option>
          <el-option label="售票中" value="1"></el-option>
          <el-option label="已售空" value="2" ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit ">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 综合新增对话框 -->
  <el-dialog v-model="addAllWinVisible" title="综合新增" width="700px">
    <el-tabs type="card">
      <!-- 演唱会信息 -->
      <el-tab-pane label="演唱会信息">
        <el-form :model="addAllForm.concert" label-width="120px">
          <el-form-item label="演唱会标题">
            <el-input v-model="addAllForm.concert.title" placeholder="请输入演唱会标题" />
          </el-form-item>
          <el-form-item label="艺人/乐队名称">
            <el-input v-model="addAllForm.concert.artist" placeholder="请输入艺人/乐队名称" />
          </el-form-item>
          <el-form-item label="开售时间">
            <el-date-picker
                v-model="addAllForm.concert.startsale"
                type="datetime"
                placeholder="请选择开售时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="演唱会开始时间">
            <el-date-picker
                v-model="addAllForm.concert.startdate"
                type="datetime"
                placeholder="请选择演唱会开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="演唱会结束时间">
            <el-date-picker
                v-model="addAllForm.concert.enddate"
                type="datetime"
                placeholder="请选择演唱会结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="演唱会简介">
            <el-input
                v-model="addAllForm.concert.introduction"
                type="textarea"
                :rows="3"
                placeholder="请输入演唱会简介" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="addAllForm.concert.status" placeholder="请选择状态">
              <el-option label="未开售" value="0"></el-option>
              <el-option label="售票中" value="1"></el-option>
              <el-option label="已售空" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 场地信息 -->
      <el-tab-pane label="场地信息">
        <el-form :model="addAllForm.venue" label-width="120px">
          <el-form-item label="场地名称">
            <el-input v-model="addAllForm.venue.name" placeholder="请输入场地名称" />
          </el-form-item>
          <el-form-item label="场地地址">
            <el-input v-model="addAllForm.venue.address" placeholder="请输入场地地址" />
          </el-form-item>
          <el-form-item label="总容量">
            <el-input v-model="addAllForm.venue.capacity" placeholder="请输入总容量" />
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input v-model="addAllForm.venue.contact" placeholder="请输入联系方式" />
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 座位信息 -->
      <el-tab-pane label="座位信息">
        <el-form :model="addAllForm.seat" label-width="120px">
          <el-form-item label="区域">
            <el-select v-model="addAllForm.seat.area" placeholder="请选择区域">
              <el-option label="VIP区" value="VIP区" />
              <el-option label="A区" value="A区" />
              <el-option label="B区" value="B区" />
              <el-option label="内场" value="内场" />
              <el-option label="看台" value="看台" />
            </el-select>
          </el-form-item>
          <el-form-item label="票数">
            <el-input v-model="addAllForm.seat.count" placeholder="请输入票数" />
          </el-form-item>
          <el-form-item label="容量">
            <el-input v-model="addAllForm.seat.capacity" placeholder="请输入容量" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="addAllForm.seat.status" placeholder="请选择状态">
              <el-option label="可售" value="0"></el-option>
              <el-option label="售空" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addAllCancel">取消</el-button>
        <el-button type="primary" @click="addAllCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>


</template>

<style scoped>

</style>